import com.sun.javafx.css.converters.PaintConverter;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

public class ExprExercise {
    private int index = 0;
    public int expr(String s) {
        return cal(s.toCharArray());
    }

    private int cal(char[] ch) {
        Deque<Integer> stack = new ArrayDeque<>();
        int num = 0;
        char sign = '+';
        while (index < ch.length) {
            System.out.println("index = " + index);
            char c = ch[index];
            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            }
            if (c == '(') {
                index++; // index指针指到下一个字符
                num = cal(ch);
            }

            // 当遇到了新的运算符，就要对上一个运算符sign和累计的数字num作运算
            // 空格直接无视，i继续前进
            // 遇到字符串末尾，肯定是要结算的
            if (!Character.isDigit(c) && c != ' ' || index == ch.length - 1) {
                // int pre = 0;
                if (sign == '+') {
                    stack.push(num);
                } else if (sign == '-') {
                    stack.push(-num);
                } else if (sign == '*') {
                    stack.push(stack.pop() * num);
                } else if (sign == '/') {
                    stack.push(stack.pop() / num);
                }
                sign = c;
                num = 0;
            }
            index++;
//            if (c == ')') {
//                continue;  //阶段，后面开始计算局部结果，返回
//            }
        }

        int res = 0;
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        System.out.println("res = " + res);
        return res;
    }
}

